package com.onlyxiahui.aware.extend.spring.cloud.feign.codec;

import static feign.Util.UTF_8;

import java.lang.reflect.Type;

import com.alibaba.fastjson.JSONObject;
import com.onlyxiahui.common.message.Message;
import com.onlyxiahui.common.message.node.Head;
import com.onlyxiahui.common.message.push.PushBodyMessage;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;

/**
 * Description <br>
 * Date 2020-05-13 21:01:04<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class DataEncoder implements Encoder {

	@Override
	public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
		String body = null;
		if (object instanceof Message) {
			body = JSONObject.toJSONString(object);
			byte[] bodyData = body != null ? body.getBytes(UTF_8) : null;
			template.body(bodyData, UTF_8);
		} else {
			Head head = new Head() {
				@Override
				public void setKey(String key) {

				}

				@Override
				public String getKey() {
					return System.currentTimeMillis() + "";
				}

			};
			PushBodyMessage<Object> pm = new PushBodyMessage<>();
			pm.setHead(head);
			pm.setBody(object);
			body = JSONObject.toJSONString(pm);
			byte[] bodyData = body != null ? body.getBytes(UTF_8) : null;
			template.body(bodyData, UTF_8);
			// .body(Request.Body.encoded(bodyData, UTF_8));
		}

		// SpringEncoder
		// GsonDecoder gsonDecoder=new GsonDecoder();
		// ResponseEntityDecoder
		// System.out.println(bodyType);
		// System.out.println(object);
	}
}
